package dao;

import lombok.Data;
import lombok.Setter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pojo.Account;

import java.util.List;
@Data
public class AccountDaoImpl implements AccountDao{
    private JdbcTemplate jdbcTemplate;
    @Override
    public int addAccount(Account account) {
        String sql = "insert into account (username,balance) values (?,?)";
        int update = jdbcTemplate.update(sql, account.getUsername(), account.getBalance());
        return update;
    }

    @Override
    public int deleteAccount(int id) {
        String sql="delete from account where id = ?";
        return jdbcTemplate.update(sql,id);
    }

    @Override
    public Account findAccount(int id) {
        String sql = "select * from account where id=?";
        return jdbcTemplate.queryForObject(sql,new AccountRowMapper(),id);
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select * from account";
        System.out.println(jdbcTemplate);
        return jdbcTemplate.query(sql,new AccountRowMapper());
    }

    @Override
    public int updateAccount(Account account) {
        String sql = "update account set username=?,balance=? where id=?";
        Object[] args={account.getUsername(),account.getBalance(),account.getId()};
        return jdbcTemplate.update(sql,args);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,
    isolation = Isolation.DEFAULT,readOnly = false)
    public void transfer(String outUser, String inUser, Double money) {
        jdbcTemplate.update("update account set balance = balance+? where username =?",money,inUser);
        int i=1/0;
        jdbcTemplate.update("update account set balance = balance-? where username =?",money,outUser);
    }
}
